package cn.tedu._03vehicle.base.exception;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.validation.ConstraintViolationException;

//@ControllerAdvice
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException: " + data);
        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }

    @ExceptionHandler
//    @ResponseBody
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex) {
        String data = ex.getMessage();
        log.error("IllegalArgumentException: " + data);
        return new JsonResult(StatusCode.OPERATION_FAILED, data);
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        String str = ex.getMessage();
        String[] result = str.split(":");
        String data = result[1].trim();
        log.error("ConstraintViolationException: " + data);
        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }

    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException ex) {
        String data = ex.getMessage();
        log.error("RuntimeException: " + data);
        return new JsonResult(StatusCode.OPERATION_FAILED, data);
    }

    @ExceptionHandler
    public JsonResult doHandleThrowable(Throwable ex) {
        String data = ex.getMessage();
        log.error("Throwable: " + data);
        return new JsonResult(StatusCode.THROWABLE_ERROR, data);
    }
}
